import express from 'express'
import cors from 'cors'
import dotenv from 'dotenv'
import path from 'path'
import { connectDB } from './config/database'
import authRoutes from './routes/auth'
import noteRoutes from './routes/notes'
import uploadRoutes from './routes/upload'
import { errorHandler } from './middleware/errorHandler'

dotenv.config()

const app = express()
const PORT = Number(process.env.PORT) || 3000

// 中间件
app.use(cors())
app.use(express.json({ limit: '10mb' }))
app.use(express.urlencoded({ extended: true }))

// 静态文件服务 - 提供上传的图片访问
app.use('/uploads', express.static(path.join(process.cwd(), 'uploads')))

// 数据库连接
connectDB()

// 路由
app.use('/api/auth', authRoutes)
app.use('/api/notes', noteRoutes)
app.use('/api/upload', uploadRoutes)

// 错误处理中间件
app.use(errorHandler)

// 健康检查
app.get('/health', (req, res) => {
  return res.json({ status: 'OK', message: 'Web Notes API is running' })
})

app.listen(PORT, '0.0.0.0', () => {
  console.log(`🚀 服务器运行在端口 ${PORT}`)
  console.log(`🌐 API地址: http://localhost:${PORT}`)
  console.log(`🔗 健康检查: http://localhost:${PORT}/health`)
})